﻿using JinJun.EF.Permission.DAL;
using JinJun.EF.Permission.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace JinJun.EF.Permission.BLL
{
  public  class AdminUserService : BaseService<AdminUser>
    {
        /// <summary>
        /// 多表插入AdminUser,AdminUserRole,ModuleUser
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="roleId"></param>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public int Add( AdminUser entity,int roleid,int moduleid,Expression<Func<AdminUser, bool>> lambdaExpression)
        {
            if (Exists(lambdaExpression)==false)
            {           
            //创建实例
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //第一种事务
                        //添加第一张表
                        db.AdminUser.Add(entity);
                        //保存
                        db.SaveChanges();

                        //添加第二张表
                        AdminUserRole adminUserRole = new AdminUserRole();
                        adminUserRole.RoleId = roleid;
                        adminUserRole.AdminUserId = entity.Id;
                        db.AdminUserRole.Add(adminUserRole);

                        //添加第三张表
                        ModuleUser moduleUser = new ModuleUser();
                        moduleUser.CreateTime = DateTime.Now;
                        moduleUser.AdminUserId = entity.Id;
                        moduleUser.ModuleId = moduleid;
                        db.ModuleUser.Add(moduleUser);
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //回滚
                        tran.Rollback();
                        //throw ex.InnerException;
                        return 3;
                    }
                }

            }
            }
            else
            {
                return 2;
            }
            return 1;
        }



        /// <summary>
        /// 多表更新
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="roleid"></param>
        /// <param name="moduleid"></param>
        /// <param name="lambdaExpression"></param>
        /// <returns></returns>
        public int AdminUpdate(AdminUser entity, int roleid, int moduleid,int arid,int maid)
        {
            
                //创建实例
                using (var db = new PermissionEntities())
                {
                    using (var tran = db.Database.BeginTransaction())
                    {
                        try
                        {
                            //第一种事务
                            //添加第一张表
                            db.Entry(entity).State = EntityState.Modified; 
                            //保存
                            db.SaveChanges();

                            //添加第二张表
                            AdminUserRole adminUserRole = new AdminUserRole();
                            adminUserRole.Id = arid;
                            adminUserRole.RoleId = roleid;
                            adminUserRole.AdminUserId = entity.Id;
                            db.Entry(adminUserRole).State = EntityState.Modified;

                            //添加第三张表
                            ModuleUser moduleUser = new ModuleUser();
                            moduleUser.Id = maid;
                            moduleUser.AdminUserId = entity.Id;
                            moduleUser.ModuleId = moduleid;
                            db.Entry(moduleUser).State = EntityState.Modified;
                            //保存
                            db.SaveChanges();
                            //提交
                            tran.Commit();
                        }
                        catch (Exception ex)
                        {
                            //回滚
                            tran.Rollback();
                            //throw ex.InnerException;
                            return 5;
                        }
                    }

                }
           
            return 4;
        }



        /// <summary>
        /// 多表删除
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="arid"></param>
        /// <param name="maid"></param>
        /// <returns></returns>
        public bool Admindelete(AdminUser entity, int arid, int maid)
        {

            //创建实例
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {

                        //添加第一张表
                            db.AdminUser.Attach(entity);
                        db.AdminUser.Remove(entity);
                        //保存
                        db.SaveChanges();

                        //添加第二张表
                        AdminUserRole adminUserRole = new AdminUserRole();
                        adminUserRole.Id = arid;                        
                        adminUserRole.AdminUserId = entity.Id;
                        db.AdminUserRole.Attach(adminUserRole);
                        db.AdminUserRole.Remove(adminUserRole);

                        //添加第三张表
                        ModuleUser moduleUser = new ModuleUser();
                        moduleUser.Id = maid;
                        moduleUser.AdminUserId = entity.Id;
                        db.ModuleUser.Attach(moduleUser);
                        db.ModuleUser.Remove(moduleUser);
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //回滚
                        tran.Rollback();
                        throw ex.InnerException;
                        return false;
                    }
                }

            }

            return true;
        }




        /// <summary>
        /// 多表连接查询
        /// </summary>
        /// <returns></returns>
        public List<AdminUserQuery> GetAdminUserList(string username, string adddate)
        {
            
            //创建List对象
            List<AdminUserQuery> adminUserQueries = new List<AdminUserQuery>();
            int mid = Convert.ToInt32(username);
            int aid= Convert.ToInt32(adddate);
            //创建实例
            using (var db = new PermissionEntities())
            {
                if (username == null&& adddate==null)
                {
                var result = from a in db.AdminUser
                             join b in db.ModuleUser
                             on a.Id equals b.AdminUserId
                             join c in db.Module
                             on b.ModuleId equals c.Id
                             join d in db.AdminUserRole
                             on a.Id equals d.AdminUserId
                             join e in db.Role
                             on d.RoleId equals e.Id                             
                             select new AdminUserQuery()
                             {
                                 Id=a.Id,
                                 AdminName = a.Name,
                                 Name=a.EmployeeName,
                                 CreateTime =a.CreateTime,
                                 ModuleName = c.Name,
                                 RoleName = e.Name,
                                 Enabled = a.Enabled,
                                 Email=a.Email,
                                 Remark=a.Remark,
                                 ARId=d.Id,
                                 MAId=b.Id
                             };
                    return result.ToList();

                }
                else if(username!=null)
                {
                    var result = from a in db.AdminUser
                                 join b in db.ModuleUser
                                 on a.Id equals b.AdminUserId
                                 join c in db.Module
                                 on b.ModuleId equals c.Id
                                 join d in db.AdminUserRole
                                 on a.Id equals d.AdminUserId
                                 join e in db.Role
                                 on d.RoleId equals e.Id
                                 where b.ModuleId== mid
                                 select new AdminUserQuery()
                                 {
                                     Id = a.Id,
                                     AdminName = a.Name,
                                     Name = a.EmployeeName,
                                     CreateTime = a.CreateTime,
                                     ModuleName = c.Name,
                                     RoleName = e.Name,
                                     Enabled = a.Enabled,
                                     Email = a.Email,
                                     Remark = a.Remark,
                                     ARId = d.Id,
                                     MAId = b.Id
                                 };
                    return result.ToList();
                }else{
                    var result = from a in db.AdminUser
                                 join b in db.ModuleUser
                                 on a.Id equals b.AdminUserId
                                 join c in db.Module
                                 on b.ModuleId equals c.Id
                                 join d in db.AdminUserRole
                                 on a.Id equals d.AdminUserId
                                 join e in db.Role
                                 on d.RoleId equals e.Id
                                 where b.ModuleId == mid&&d.RoleId==aid
                                 select new AdminUserQuery()
                                 {
                                     Id = a.Id,
                                     AdminName = a.Name,
                                     Name = a.EmployeeName,
                                     CreateTime = a.CreateTime,
                                     ModuleName = c.Name,
                                     RoleName = e.Name,
                                     Enabled = a.Enabled,
                                     Email = a.Email,
                                     Remark = a.Remark,
                                     ARId = d.Id,
                                     MAId = b.Id
                                 };
                    return result.ToList();
                }
              
            }
        }


        /// <summary>
        /// 返回组的集合
        /// </summary>
        /// <param name="lambdaExpression"></param>
        /// <returns></returns>
        public List<Module> Getmodulelist(Expression<Func<Module, bool>> lambdaExpression)
        {
            BaseRepository<Module, PermissionEntities> baseRepository = new BaseRepository<Module, PermissionEntities>();
            return baseRepository.QueryList(lambdaExpression);
        }


        /// <summary>
        /// 根据组Id查询对应的角色名
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public List<Role> Getrolename(ModuleRole moduleRole)
        {
            using (var db = new PermissionEntities())
            {
                var result = from a in db.Role
                             join c in db.ModuleRole
                             on a.Id equals c.RoleId
                             where c.ModuleId == moduleRole.ModuleId
                             select a;
                             
                
                return result.ToList();
            }
        }



        public override bool AddRange(List<AdminUser> entities)
        {
            return base.AddRange(entities);
        }

        public override bool BatchDelete(List<AdminUser> entities)
        {
            return base.BatchDelete(entities);
        }

        public override bool BatchDeleteById(params int[] ids)
        {
            return base.BatchDeleteById(ids);
        }

        public override bool Delete(AdminUser entity)
        {
            return base.Delete(entity);
        }

        public override bool Exists(Expression<Func<AdminUser, bool>> lambdaExpression)
        {
            return base.Exists(lambdaExpression);
        }

        public override AdminUser Query(Expression<Func<AdminUser, bool>> lambdaExpression)
        {
            return base.Query(lambdaExpression);
        }

        public override List<AdminUser> QueryList(Expression<Func<AdminUser, bool>> lambdaExpression)
        {
            return base.QueryList(lambdaExpression);
        }

        public override List<AdminUser> QueryPageList<S>(int pageIndex, int pageSize, Expression<Func<AdminUser, bool>> whereLambda, Expression<Func<AdminUser, S>> orderbyLambda, out int count, bool isAsc = true)
        {
            return base.QueryPageList(pageIndex, pageSize, whereLambda, orderbyLambda, out count, isAsc);
        }

        public override bool Update(AdminUser entity)
        {
            return base.Update(entity);
        }
    }
}
